import {reactive} from 'vue'
import bus from '../../public/bus'
import { playAudio } from './webServer'
let chessPiecedata:any = reactive({
	whiteData:[],
	blackData:[],
	historyPoint:{},
	width:0,
})
// 绘制圆
export const useCrice = (context:any,point:any,color:string = '#000',radius = 2)=>{
	context.beginPath()
	context.arc(point[0], point[1],radius,0,2*Math.PI);
	context.fillStyle = color;
	context.fill();
}
// 擦除
export const useErasure = (chessboardCanvas:any,context:any,params:any,data:any)=>{
	context.clearRect(0,0,chessPiecedata.width,chessPiecedata.width);
	useChessboard(chessboardCanvas,chessPiecedata.width,chessPiecedata.width,1)
	params.baseData.totalData.forEach((v:any)=>{
		v.forEach((n:any)=>{
			if(n[2]){
				if(n[2] === 1){
					useCrice(context,n,'#000',params.vInterval/3.5)
				}else{
					useCrice(context,n,'#fff',params.vInterval/3.5)
				}
				
			}
		})
	})
	
}
// 历史记录
export const useRecordChess = (params:any,record:any)=>{
	console.log(record.blackData)
	record.blackData.forEach((s:any)=>{
		let currentPoint = params.baseData.totalData[s[0]][s[1]]
		useCrice(params.context,currentPoint,'#000',params.vInterval/3.5)
	})
	record.whiteData.forEach((s:any)=>{
		let currentPoint = params.baseData.totalData[s[0]][s[1]]
		useCrice(params.context,currentPoint,'#fff',params.vInterval/3.5)
	})
	
}
// 检测是否开始下棋
export const useIsStartchess = (data:any)=>{
	let regretPoint = []
	if(data.currentChess === 1){
		regretPoint = chessPiecedata.blackData
	}else{
		regretPoint = chessPiecedata.whiteData
	}
	console.log(data.currentChess)
	return regretPoint.length
}
// 获取当前棋局
export const useGetchess = (data:any)=>{
	return chessPiecedata
}
// 悔棋
export const useRegret = (chessboardCanvas:any,params:any,data:any,type:number)=>{
	let regretPoint = []
	let currentChess = data.currentChess
	if(type === 1){
		currentChess = data.currentChess === 1?2:1
		chessPiecedata.historyPoint = {}
	}
	if(currentChess === 1){
		regretPoint = chessPiecedata.blackData[chessPiecedata.blackData.length - 1]
	}else{
		regretPoint = chessPiecedata.whiteData[chessPiecedata.whiteData.length - 1]
	}
	params.baseData.totalData[regretPoint[0]][regretPoint[1]].pop()
	useErasure(chessboardCanvas,params.context,params,data)
	
}

// 棋盘绘制
export const useChessboard = (chessboardCanvas:any,width:number,height:number,type:number)=>{
	
	let baseData:any = reactive({
		totalData:[]
	})
	if(!type){
		chessPiecedata.whiteData = []
		chessPiecedata.blackData = []
		chessPiecedata.historyPoint = {}
	}
	// chessboardCanvas.value.width = width
	// chessboardCanvas.value.height = height
	width = height
	height = height
	chessboardCanvas.value.width = width
	chessboardCanvas.value.height = width
	chessPiecedata.width = width
	const context = chessboardCanvas.value?.getContext('2d')
	
	// let padding = 30  //边距
	// let interval = 26 //线条数量
	// let hInterval = (height-padding*2) / interval //横线间隔
	// let vInterval = (width-padding*2) / interval //竖线间隔
	
	let padding = 30  //边距
	let interval = 20 //线条数量
	let hInterval = (width-padding*2) / interval //横线间隔
	let vInterval = (height-padding*2) / interval //竖线间隔
	
	// 画横线
	for(let h = 0; h < interval + 1; h++){
	  context.beginPath()
	  context.moveTo(padding,padding + hInterval*h);
	  context.lineTo(width - padding,padding + hInterval*h);
	  context.strokeStyle = "#af8a52";
	  context.strokeWidth = 1
	  context.lineWidth =  1
	  context.stroke();
	  baseData.totalData[h] = []
	  for(let v = 0; v < interval + 1; v++){
		  baseData.totalData[h][v] = []
		  baseData.totalData[h][v] = [padding + vInterval*v,padding + hInterval*h]
	  }
	  
	}
	// 画竖线
	for(let h = 0; h < interval + 1; h++){
	  context.beginPath()
	  context.moveTo(padding+vInterval*h,padding);
	  context.lineTo(padding+vInterval*h,height - padding);
	  context.strokeStyle = "#af8a52";
	  context.strokeWidth = 1
	  context.lineWidth =  1
	  context.stroke();
	}
	// 绘制中心点
	let x = (interval)/2
	let y = (interval)/2
	let center = baseData.totalData[x][y]
	let topLeftPos = baseData.totalData[x - 9][y - 9]
	let topRightPos = baseData.totalData[x - 9][y + 9]
	let bottomLeftPos = baseData.totalData[x + 9][y - 9]
	let bottomRightPos = baseData.totalData[x + 9][y + 9]
	useCrice(context,center)
	useCrice(context,topLeftPos)
	useCrice(context,topRightPos)
	useCrice(context,bottomLeftPos)
	useCrice(context,bottomRightPos)
	return {
		context,
		baseData,
		hInterval,
		vInterval
	}
}

// 计算胜负 i第一级 k第二级
export const useCalculate = (baseData:any,i:number,k:number)=>{
	let totalData =  baseData.totalData
	
	let currentType = totalData[i][k][2]
	let count = 0
	let win = 0
	try{
		// 横排
		for(let j = 0;j < totalData[i].length;j++){
			totalData[i][j][2] == currentType?count++:count = 0
			if(count >= 5){
				win = 1
				break
			}
		}
		// 竖排
		for(let j = 0;j < totalData.length;j++){
			totalData[j][k][2] == currentType?count++:count = 0
			if(count >= 5){
				win = 1
				break
			}
		}
		
		// 左上
		let z = k
		for(let j = i-1;j >= 0;j--){
			if(totalData[j][--z][2] == currentType){
				count++
				if(count >= 4){
					win = 1
					break
				}
			}else{
				break
			}
		}
		// 左下
		z = k
		for(let j = i + 1;j <= totalData.length;j++){
			if(totalData[j][++z][2] == currentType){
				count++
				if(count >= 4){
					win = 1
					break
				}
			}else{
				count = 0
				break
			}
		}
		// 右上
		z = k
		for(let j = i-1;j >= 0;j--){
			if(totalData[j][++z][2] == currentType){
				count++
				if(count >= 4){
					win = 1
					break
				}
			}else{
				break
			}
		}
		// 右下
		z = k
		for(let j = i + 1;j <= totalData.length;j++){
			if(totalData[j][--z][2] == currentType){
				count++
				if(count >= 4){
					win = 1
					break
				}
			}else{
				count = 0
				break
			}
		}
	}catch(e:any){
		
	}
	if(!win){
		return false
	}else{
		return currentType
	}
}
// 计算是否存在多个棋子
function getChessTotal (baseData:any,i:number,k:number,countTotal:number){
	let totalData =  baseData
	
	let currentType = totalData[i][k][2]
	let count = 1
	let win = 0
	let pointArray = []
	console.log('currentType',currentType,countTotal - 1,i,k)
	try{
		// 横排
		for(let j = 0;j < totalData[i].length;j++){
			totalData[i][j][2] == currentType?count++:count = 0
			if(count >= countTotal){
				win = 1
				pointArray.push({
					point:[i,j],
					count:count
				})
				break
			}
		}
		// 竖排
		count = 0
		for(let j = 0;j < totalData.length;j++){
			totalData[j][k][2] == currentType?count++:count = 0
			if(count >= countTotal){
				win = 1
				pointArray.push({
					point:[j,k],
					count:count
				})
				break
			}
		}
		
		// 左上
		let z = k
		count = 0
		for(let j = i-1;j >= 0;j--){
			if(totalData[j][--z][2] == currentType){
				count++
				if(count >= countTotal - 1){
					win = 1
					pointArray.push({
						point:[j,z],
						count:count
					})
					break
				}
			}else{
				break
			}
		}
		// 左下
		z = k
		count = 0
		for(let j = i + 1;j <= totalData.length;j++){
			if(totalData[j][++z][2] == currentType){
				count++
				if(count >= countTotal - 1){
					win = 1
					pointArray.push({
						point:[j,z],
						count:count
					})
					break
				}
			}else{
				count = 0
				break
			}
		}
		// 右上
		z = k
		count = 0
		for(let j = i-1;j >= 0;j--){
			if(totalData[j][++z][2] == currentType){
				count++
				if(count >= countTotal - 1){
					
					win = 1
					pointArray.push({
						point:[j,z],
						count:count
					})
					break
				}
			}else{
				break
			}
		}
		// 右下
		z = k
		count = 0
		for(let j = i + 1;j <= totalData.length;j++){
			
			if(totalData[j][--z][2] == currentType){
				count++
				if(count >= countTotal - 1){
					win = 1
					pointArray.push({
						point:[j,z],
						count:count
					})
					break
				}
			}else{
				count = 0
				break
			}
		}
	}catch(e:any){
		
	}
	
	return pointArray
}

// 人机算法黑
export const useManMachineAlgorithm = (d:[any],totalData:any,dCount:number = 3,computerValue:any = null)=>{
	let [x,y] = computerValue?computerValue:d[d.length - 1]
	let length = totalData.length - 1
	let count = 0 //统计对方棋子数量
	let pointMessage:any = {
		h:[],
		s:[],
		r:[],
		l:[]
	} //获取位置
	// 横排
	let addType = dCount === 3?1:2
	let restoreType = dCount === 3?2:1
	let isUndefine = 0
	totalData[x].forEach((v:number[],i:number)=>{
		
		if(v[2] === restoreType || !v[2] && addType === 2){
			count = 0
			isUndefine = 0
		}
		if(addType === 1){
			if(!v[2] && isUndefine === 1){
				count = 0
				isUndefine = 0
			}
			if(!v[2] && !isUndefine){
				isUndefine = 1
			}
		}
		if(v[2] === addType){
			count++
		}
		if(count >= dCount){	
			pointMessage.h = [x,i,count]
		}
		
	})
	// 竖排
	count = 0
	isUndefine = 0
	totalData[x].forEach((v:number[],i:number)=>{
		
		if(totalData[i][y][2] === restoreType || !totalData[i][y][2] && addType === 2){
			count = 0
			isUndefine = 0
		}
		
		if(addType === 1){
			if(!totalData[i][y][2] && isUndefine === 1){
				count = 0
				isUndefine = 0
			}
			if(!totalData[i][y][2] && !isUndefine){
				isUndefine = 1
			}
			
		}
		if(totalData[i][y][2] === addType){
			count++
		}
		if(count >= dCount){
			pointMessage.s = [i,y,count]
		}
		
	})
	// 右下
	let rx = y > x?0:y < x?x - y:0
	let ry = y > x?y - x:y < x?0:0
	count = 0
	isUndefine = 0
	for(let i = rx; i <= length; i++){
		
		if(!totalData[i]||!totalData[i][ry]){
			break
		}
		
		if(totalData[i][ry][2] === restoreType  || !totalData[i][ry][2] && addType === 2){
			count = 0
			isUndefine = 0
		}
		if(addType === 1){
			if(!totalData[i][ry][2] && isUndefine === 1){
				count = 0
				isUndefine = 0
			}
			if(!totalData[i][ry][2] && !isUndefine){
				isUndefine = 1
			}
		}
		if(totalData[i][ry][2] === addType){
			count++
		}
		if(count >= dCount){
			pointMessage.r = [i,ry,count]
		}
		
		ry++
	}
	// 左下
	let lx = x + y > length? x + y - length:x + y === length?0:0
	let ly = x + y > length?length:x + y === length?length:x + y
	count = 0
	isUndefine = 0
	for(let i = lx; i <= length; i++){
		
		if(!totalData[i]||!totalData[i][ly]){
			break
		}
		
		if(totalData[i][ly][2] === restoreType || !totalData[i][ly][2] && addType === 2){
			count = 0
			isUndefine = 0
		}
		if(addType === 1){
			if(!totalData[i][ly][2] && isUndefine === 1){
				count = 0
				isUndefine = 0
			}
			if(!totalData[i][ly][2] && !isUndefine){
				isUndefine = 1
			}
		}
		
		if(totalData[i][ly][2] === addType){
			count++
		}
		if(count >= dCount){
			pointMessage.l = [i,ly,count]
		}
		
		ly--
	}
	console.log(pointMessage)
	return pointMessage
}
// 返回黑白棋测算的坐标
function getWhiteBlackPoint(result:any,totalData:any,m:number):any{
	let x:any = null
	let y :any = null
	let arr:any = []
	let saveArr:any = {}
	if(result.h.length > 0){
		arr.push({
			size:result.h[2],
			type:1
		})
		
	}
	if(result.s.length > 0){
		arr.push({
			size:result.s[2],
			type:2
		})
		
	}
	if(result.r.length > 0){
		arr.push({
			size:result.r[2],
			type:3
		})
	}
	if(result.l.length > 0){
		arr.push({
			size:result.l[2],
			type:4
		})
	}
	let type = 0
	if(arr.length > 0){
		arr.sort(function(a:any, b:any) { return a.size - b.size })
		type = arr[arr.length - m]?.type
	}
	if(result.h.length > 0 && type === 1){
		x = result.h[0]
		y = result.h[1] + 1
		if(!totalData[x] || totalData[x][y]&&totalData[x][y][2]){
			x = result.h[0]
			y = result.h[1] - result.h[2]
			if(totalData[x][y][2]){
				x = null
				y = null
			}
		}
	}
	if(result.s.length > 0 && type === 2){
		x = result.s[0] + 1
		y = result.s[1]
		console.log(x,y,totalData)
		if(!totalData[x] || totalData[x][y]&&totalData[x][y][2]){
			x = result.s[0] - result.s[2]
			y = result.s[1]
			if(totalData[x][y][2]){
				x = null
				y = null
			}
		}
	}
	if(result.r.length > 0 && type === 3){
		x = result.r[0] + 1
		y = result.r[1] + 1
		if(!totalData[x] || totalData[x][y]&&totalData[x][y][2]){
			x = result.r[0] - result.r[2]
			y = result.r[1] - result.r[2]
			if(totalData[x][y][2]){
				x = null
				y = null
			}
		}
	}
	if(result.l.length > 0 && type === 4){
		x = result.l[0] + 1
		y = result.l[1] - 1
		console.log(x,y,totalData)
		if(!totalData[x] || totalData[x][y]&&totalData[x][y][2]){
			x = result.l[0] - result.l[2]
			y = result.l[1] + result.l[2]
			if(totalData[x][y][2]){
				x = null
				y = null
			}
		}
	}
	
	if(type && x === null){
		return getWhiteBlackPoint(result,totalData,++m)
	}else{
		console.log(66666,x,y)
		return {
			x,
			y,
			size:arr[arr.length - m]?.size
		}
	}
	
}
function totalChessComputer(whiteBlackData:any,totalData:any){
	let chessTotalResult:any = null
	let r:number = 0
	let computerValue:any = null
	for(let i = 5;i > 0; i--){
		chessTotalResult = []
		whiteBlackData.forEach((v:number[])=>{
			let s = getChessTotal(totalData,v[0],v[1],i)
			if(s.length > 0){
				chessTotalResult.push(s)
			}
		})
		if(chessTotalResult.length > 0){
			break
		}
	}
	if(chessTotalResult&&chessTotalResult.length > 0){
		r = Math.floor(Math.random() * (chessTotalResult.length - 1))
		computerValue = chessTotalResult[r][0]?.point
	}
	return computerValue
}
// 人机
export const useManMachine = (totalData:any)=>{

		let blackData = chessPiecedata.blackData
		let whiteData = chessPiecedata.whiteData
		let x:any = null
		let y:any = null
		let computerValue = totalChessComputer(blackData,totalData)
		let result = useManMachineAlgorithm(blackData,totalData,3,computerValue)
		let g:any = getWhiteBlackPoint(result,totalData,1)
		x = g?.x
		y = g?.y
		console.log(555553333333,g)
		if(chessPiecedata.whiteData.length === 0){
			let m = blackData.pop()
			let bx = m[0]
			let by = m[1]
			function k(){
				let r = Math.floor(Math.random() * 3)
				x = r === 0?bx:r === 1?bx:r === 2?bx - 1:bx + 1
				y = r === 0?by - 1:r === 1?by + 1:r === 2?by:by
				if(totalData[x][y][2]){
					k()
				}
			}
			k()
		}else{
			
			computerValue = totalChessComputer(whiteData,totalData)
			let whiteResult = useManMachineAlgorithm(whiteData,totalData,1,computerValue)
			let whiteBlackPointResult = getWhiteBlackPoint(whiteResult,totalData,1)
			if( x === null){
				g = whiteBlackPointResult
				x = g?.x
				y = g?.y
			}else{
				console.log(3333333333333333333333333,whiteBlackPointResult,g)
				if(whiteBlackPointResult.size >= g.size){
					g = whiteBlackPointResult
					x = g?.x
					y = g?.y
				}
			}
		}
		if(x === null){
			function randomPoint(){
				let randomX = Math.floor(Math.random() * (totalData.length - 1))
				let randomY = Math.floor(Math.random() * (totalData[randomX].length - 1))
				if(totalData[randomX][randomY][2]){
					randomPoint()
				}else{
					x = randomX
					y = randomY
				}
			}
			randomPoint()
		}
		let d:number[] = totalData[x][y]
		return {
			d,
			x,
			y
		}
		
	
}

// 下棋 currentType判断当前是对方 2还是我方1 人机 0
export const useChessPiece = (event:any,params:any,data:any)=>{
	let {context,baseData,hInterval,vInterval,currentType,x,y} = params
	// 计算输赢,并返回值
	const t = function(d:any,i:number,k:number){
			if(data.playChess == "黑棋"){
				useCrice(context,d,"#000",vInterval/3.5)
				d[2] = 1
				data.playChess = "白棋"
				chessPiecedata.blackData[chessPiecedata.blackData.length] = [i,k]
			}else{
				useCrice(context,d,"#fff",vInterval/3.5)
				d[2] = 2
				data.playChess = "黑棋"
				chessPiecedata.whiteData[chessPiecedata.whiteData.length] = [i,k]
			}
			console.log(chessPiecedata,baseData.totalData)
			if(currentType === 2){
				if(chessPiecedata.historyPoint?.c){
					let v = chessPiecedata.historyPoint
					useCrice(v.context,v.d,v.c,v.r)
				}
				useCrice(context,d,"red",vInterval/3.5/6)
				chessPiecedata.historyPoint = {
					context:context,
					d:d,
					c:d[2],
					r:vInterval/3.5
				}
			}
			let w = useCalculate(baseData,i,k)
			let s = Object.assign({},chessPiecedata)
			if(w){
				chessPiecedata.blackData = []
				chessPiecedata.whiteData = []
			}
			bus.emit('win',JSON.stringify({
				w,
				baseData,
				context,
				i,
				k,
				s
			}))
			playAudio(1)
	}
	
	
	if(currentType == 1){
		let {offsetX,offsetY} = event
		baseData.totalData.forEach((v:any,i:number)=>{
			v.forEach((d:any,k:number)=>{
				if(d[2]){
					return
				}
				if(Math.abs(d[0] - offsetX) < hInterval/4 && Math.abs(d[1] - offsetY) < vInterval/4){
					if(d[2]){
						return
					}
					t(d,i,k)
					setTimeout(()=>{
						if(data.opposite.account === 'admin'){
							let c = useManMachine(baseData.totalData)
							if(c){
								let {d,x,y} = c
								t(d,x,y)
								bus.emit('isMachine',1)
							}
						}
					},2000)
					
				}
				
			})
		})
	}else if(currentType == 2){
		t(baseData.totalData[x][y],x,y)
	}else{
		let c = useManMachine(baseData.totalData)
		if(c){
			let {d,x,y} = c
			t(d,x,y)
		}
	}
}
// 清除棋盘
export const clearChesspiece = ()=>{
	
}

// 计时器
let timing:any = null
export const useTiming = (...args:any)=>{
	if(!args[0]){
		if(timing){
			clearInterval(timing)
		}
		return
	}
	let count = args[0]
	if(timing){
		clearInterval(timing)
	}
	
	return (function t (){
		timing = setInterval(()=>{
			if(count > 1){
				count--
			}else{
				clearInterval(timing)
				count = args[0]
				t()
			}
			if(typeof args[1] == 'function'){
				args[1](count)
			}
		},1000)
	})()
}